#include<bits/stdc++.h>
using namespace std;
#define int long long

struct edge {
	int endPoint, distance;
};

int n, m;
vector<edge> e[105];	// 从 i 点出发到e[i].endPoint 的距离为e[i].distance

struct node {
	int point, distance;
	bool operator < (const node &x)const {
		return distance > x.distance;
	}
};

bool vis[105];

int prim() {
	priority_queue<node> q;
	q.push({1, 0});

	int ans = 0, cnt = 0;

	while (!q.empty()) {
		node t = q.top();
		q.pop();

		if (vis[t.point])	continue;
		vis[t.point] = 1;

		ans += t.distance;
		cnt++;

		int flag = 0;
		for (auto i : e[t.point]) {
			if (vis[i.endPoint])	continue;
			q.push({i.endPoint, i.distance});
			flag = 1;
		}
//		if (!flag)
//			return -1;
	}
	return ans;
}

bool check() {
	for (int i = 1; i <= n; i++)
		if (e[i].size() == 0)
			return false;
	return true;
}

int a[105][105];

signed main() {
	int x, y, z;
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		cin >> x >> y >> z;
		if (a[x][y])
			a[y][x] = a[x][y] = min(a[x][y], z);
		else
			a[y][x] = a[x][y] = z;
		e[x].push_back({y, z});
		e[y].push_back({x, z});
	}

	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			if (a[i][j]) {
				e[i].push_back({j, a[i][j]});
				e[j].push_back({i, a[i][j]});
			}
		}
	}

	if (!check() || m < n - 1) {
		cout << "-1";
		return 0;
	}

	cout << prim();
	return 0;
}
